﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Taxonomy;
using System.IO;

namespace VNTG.TaxonomyUploader.TaxonomyImporter
{
    public partial class TaxonomyImporterUserControl : UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {

           File1.Accept = "text/*";

            if (!Page.IsPostBack)
            {
                FillTermSToreBoxes();
                tax.Visible = false;
            }            
        }

        private void FillTermSToreBoxes()
        {
            using (SPSite s = new SPSite(SPContext.Current.Site.Url))
            {
                TaxonomySession ses = new TaxonomySession(s, false);

                dwlTermStore.DataSource = ses.TermStores;
                dwlTermStore.DataValueField = "Name";
                dwlTermStore.DataBind();
                
            }
        }

        protected void TermStore_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (dwlTermStore.SelectedItem != null)
            {
                using (SPSite s = new SPSite(SPContext.Current.Site.Url))
                {
                    TaxonomySession ses = new TaxonomySession(s, false);

                    TermStore store = ses.TermStores[dwlTermStore.SelectedValue.ToString()];

                    FillGroups(store);
                }
            }
        }

        private void FillGroups(TermStore store)
        {
            dwlGroup.DataSource = store.Groups;
            dwlGroup.DataValueField = "Name";
            dwlGroup.DataBind();
        }

        protected void cmdUpload_Click(object sender, EventArgs e)
        {
            if (File1.PostedFile.FileName == "" || File1.PostedFile.ContentLength < 1)
            {
                Status.Text = "Enter a valid file";
                return;
            }
            if (!File1.PostedFile.FileName.ToLower().EndsWith(".csv"))
            {
                Status.Text = "Only csv files";
                return;
            }

            InsertIntoTaxonomy imp = new InsertIntoTaxonomy(dwlTermStore.SelectedValue, dwlGroup.SelectedValue);

            imp.StartParseCSVAndImport(File1.PostedFile.InputStream);

            Status.Text = "Termsets and terms successfully added";
        }

        protected void dwlGroup_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (dwlGroup.SelectedItem != null)
            {
                tax.Visible = true;
            }
        }
    }
}
